<?php
class Marcas extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library(
                array(
                    'session',
                    'r_session',
                    'form_validation'
                ));
        $this->load->helper(
                array(
                    'url'
                ));
        $this->load->model(
                array(
                    'marcas_model'
                ));
        $this->r_session->check($this->session->all_userdata());
    }
    
    public function index() {
        $session = $this->session->all_userdata();
        $session['title'] = 'Listado de Marcas';
        $data['marcas'] = $this->marcas_model->get_marcas();
        
        $this->load->view('layout/header', $session);
        $this->load->view('marcas/index', $data);
        $this->load->view('layout/footer');
    }
    
    public function agregar() {
        $session = $this->session->all_userdata();
        $session['title'] = 'Agregar Marca';
        $data = array();
        
        $this->form_validation->set_rules('marca', 'Marca', 'required');
        
        if($this->form_validation->run() == FALSE) {
            
        } else {
            if($this->marcas_model->existe_marca_por_nombre($this->input->post('marca'))) {
                $data['existe'] = 'La marca '.$this->input->post('marca').' ya existe';
            } else {
                $datos = array(
                    'nombre' => $this->input->post('marca'),
                    'habilitado' => 1
                );
                
                $this->marcas_model->set_marca($datos);
                
                redirect('/marcas/', 'refresh');
            }
        }
        
        $this->load->view('layout/header', $session);
        $this->load->view('marcas/agregar', $data);
        $this->load->view('layout/footer');
    }
    
    public function update($id) {
        $session = $this->session->all_userdata();
        $session['title'] = 'Modificar Marca';
        $data['marca'] = $this->marcas_model->get_marca_por_id($id);
        
        $this->form_validation->set_rules('marca', 'Marca', 'required');
        
        if($this->form_validation->run() == FALSE) {
            
        } else {
            $datos = array(
                'nombre' => $this->input->post('marca')
            );
            
            $this->marcas_model->update($datos, $id);
            
            redirect('/marcas/', 'refresh');
        }
        
        $this->load->view('layout/header', $session);
        $this->load->view('marcas/update', $data);
        $this->load->view('layout/footer');
    }
}
?>
